<template>
  <base-layout
    :visibleSea="!$route.params.id"
    :visibleContent2="true"
    :visibleContent3="true"
    :visibleContent4="workOrderType != 2"
    :visibleContent5="workOrderType == 3"
    :visibleContent6="true"
  >
    <template
      #searchPanel
      v-if="!$route.params.id"
    >
      <CustomerSearch
        :addCustomer="true"
        :singleChoice="true"
        @clientForm="customerInfo"
      />
    </template>
    <!-- 车辆信息表单 -->
    <template #contentPanel>
      <CarInfo
        :formValue="carInfo"
        ref="carInfo"
        :workOrderType="workOrderType"
      />
    </template>
    <!-- 快捷套餐 只有工单类型是1快速单 2洗车单时显示 工单信息 只有综合单3 显示 -->
    <template #contentPanel2>
      <!-- 工单备注信息 -->
      <WorkInfoRemark
        v-if="workOrderType == 1 || workOrderType == 2"
        ref="workInfoRemark"
        :workOrderType="workOrderType"
        :formValue="fastInfo"
      />
      <el-divider content-position="center"></el-divider>
      <!-- 快捷套餐 -->
      <SetUpPackage
        v-if="workOrderType != 3"
        ref="setUpPackage"
        :workOrderType="workOrderType"
      />
      <!-- 工单信息 -->
      <WorkInfo
        v-if="workOrderType == 3"
        ref="workInfo"
        :workOrderType="workOrderType"
        :formValue="fastInfo"
      />
    </template>
    <!-- 项目列表 -->
    <template #contentPanel3>
      <WorkOrderItemList
        ref="workOrderItemList"
        @setTotalAmount="setTotalAmount"
        :workOrderType="workOrderType"
        :list="fastInfo.projectList"
      />
    </template>
    <!-- 配件列表 只有洗车单不显示 -->
    <template
      #contentPanel4
      v-if="workOrderType !== 2"
    >
      <Fitting
        ref="fitting"
        @setTotalAmount="setTotalAmount"
        :workOrderType="workOrderType"
        :list="fastInfo.partsList"
      />
    </template>
    <!-- 精品列表 只有综合但才显示 -->
    <template
      #contentPanel5
      v-if="workOrderType == 3"
    >
      <BoutiqueList
        ref="boutiqueList"
        @setTotalAmount="setTotalAmount"
        :workOrderType="workOrderType"
        :list="fastInfo.jpList"
      />
    </template>
    <!-- 保存按钮显示组块 -->
    <template #contentPanel6>
      <el-col
        :span="24"
        v-if="workOrderType == 1 || workOrderType == 3"
      >
        <el-switch
          v-model="endWash"
          active-color="#13ce66"
          active-text="完工是否需要洗车"
        >
        </el-switch>
      </el-col>
      <el-col
        :span="24"
        align="right"
      >
        <div class="amount">
          <div>
            总金额：<span class="colorF40">￥{{ totalAmount }}</span>
          </div>
          <div v-if="workOrderType == 1">
            可折扣优惠卷：
            <!-- @couponClick="couponEv" -->
            <Coupon
              ref="coupon"
              v-model="couponDiscount"
              :list="couponUseCouponList"
            >
              有{{ couponUseCouponList.length }}张可用优惠卷
            </Coupon>
          </div>
          <div v-if="workOrderType == 1">优惠卷减免：￥{{ couponDiscount }}</div>
          <!-- couponDiscount也可以作为也收款的金额 -->
          <div v-if="workOrderType == 3">已交定金总额：￥{{ couponDiscount }}</div>
          <div v-if="workOrderType != 2">
            应付金额：<span class="colorF40">￥{{ amountsPayable }}</span>
          </div>
        </div>
        <el-button
          type="primary"
          @click="saveOrEdit"
        >保存</el-button>
      </el-col>
    </template>
  </base-layout>
</template>
<script>
import CarInfo from "@/views/after-sale/workOrderManage/fast/create/CarInfo"; //拆分-车辆信息表单
import SetUpPackage from "@/views/after-sale/workOrderManage/fast/create/SetUpPackage"; //拆分-套餐设置
import WorkOrderItemList from "@/views/after-sale/workOrderManage/fast/create/WorkOrderItemList"; //拆分-项目列表
import Fitting from "@/views/after-sale/workOrderManage/fast/create/Fitting"; //拆分-配件列表
import WorkInfo from "@/views/after-sale/workOrderManage/fast/create/WorkInfo"; //拆分-综合单工单信息
import BoutiqueList from "@/views/after-sale/workOrderManage/sell/create/boutiqueList"; //拆分-精品列表
import WorkInfoRemark from "@/views/after-sale/workOrderManage/fast/create/work-info-remark"; //工单备注信息

import { couponUseCoupon } from "@/api/after-sale/client/coupon"; //查询可使用优惠卷
import baseMixin from "@/mixins/base";
import {
  addRapid,
  editRapid,
  rapidFindById,
} from "@/api/after-sale/workOrderManage/fast"; //快速单api
import {
  addWash,
  editWash,
  editWashDetail,
} from "@/api/after-sale/workOrderManage/car-wash"; //洗车单api
import {
  synthesizeFindById,
  addSynthesize,
  editSynthesize,
} from "@/api/after-sale/workOrderManage/comprehensive"; //综合单api
import { CustomerSearch, Coupon } from "@/components/index"; //导入组件库
import { getStoreId, debounce } from "@/utils";
import { getUserDiscount } from "@/utils/userDiscount";

export default {
  mixins: [baseMixin({})],
  props: {
    workOrderType: {
      type: Number,
      default: 1, //1 快速单 2 洗车单  3综合单
    },
  },
  components: {
    CustomerSearch,
    CarInfo,
    SetUpPackage,
    WorkOrderItemList,
    Fitting,
    Coupon,
    WorkInfo,
    BoutiqueList,
    WorkInfoRemark,
  },
  data () {
    return {
      carInfo: {}, //车辆信息
      dialogWidth: "1000px",
      totalAmount: 0, //工单总金额
      couponDiscount: 0, //优惠劵金额
      parentFinttingData: [],
      parentProjectList: [],
      couponUseCouponList: [], //可使用优惠劵列表
      fastInfo: {
        id: "",
      }, //快速工单详情
      debounceCoupn: "",
      pickCarId: null, // 接车单id
      endWash: false
    };
  },
  computed: {
    //应付金额
    amountsPayable () {
      return (this.totalAmount * 1 - this.couponDiscount * 1).toFixed(2);
    },
  },
  methods: {
    //设置总金额、优惠劵查询
    setTotalAmount () {
      console.log('setTotalAmount触发更新')
      let { workOrderItemList, fitting, boutiqueList } = this.$refs;
      this.totalAmount = 0;
      if (this.workOrderType === 2) {
        //洗车单
        this.totalAmount = workOrderItemList.totalAmount * 1;
      } else {
        if (workOrderItemList && "totalAmount" in workOrderItemList) {
          this.totalAmount += workOrderItemList.totalAmount * 1;
        }
        if (fitting && "totalAmount" in fitting) {
          this.totalAmount += fitting.totalAmount * 1;
        }
        if (boutiqueList && "totalAmount" in boutiqueList) {
          this.totalAmount += boutiqueList.totalAmount * 1;
        }
        this.totalAmount=this.totalAmount.toFixed(2)
        this.parentFinttingData = Object.assign([], this.$refs.fitting.finttingData);
      }
      this.parentProjectList = Object.assign(
        [],
        this.$refs.workOrderItemList.projectList
      );
      this.debounceCoupn && this.debounceCoupn();
    },
    //用户信息回传
    customerInfo (values) {
      values.sendRepairName = values.clientName;
      values.sendRepairPhone = values.phone;
      this.carInfo = values;
      if (Array.isArray(values.cars)) {
        this.carInfo.cars = values.cars[0];
      }
      let { discountInterval } = values; //获取折扣对象-包含用户权限折扣和会员卡折扣区间值
      //设置配件列表的折扣上下限
      let refsList = [
        {
          name: "workOrderItemList",
          discountFilde: "projectDiscount",
          coulumFilde: "tableColumnAttributes",
        },
      ];
      if (this.workOrderType !== 2) {
        refsList.push({
          name: "fitting",
          discountFilde: "partsDiscount",
          coulumFilde: "finttingAttributes",
        });
      }
      if (this.workOrderType == 3) {
        refsList.push({
          name: "boutiqueList",
          discountFilde: "partsDiscount",
          coulumFilde: "tableColumnAttributes",
        });
      }
      refsList.map((item) => {
        let dom = this.$refs[item.name];
        let list = dom[item.coulumFilde];
        list.forEach((item2) => {
          if (item2.value == "discount") {
            item2.maxFiled = discountInterval[item.discountFilde].max;
            item2.minFiled = discountInterval[item.discountFilde].min;
            item2.name = `折扣(当前客户折扣范围:${item2.minFiled}-${item2.maxFiled})`;
          }
        });
      });
    },
    getWorkUserList (userid) {
      let _workUserList = this.$refs.workOrderItemList.workUserList;
      let targe = _workUserList.filter((item) => {
        if (item.id == userid) {
          item.value = item.value.split("_")[0];
          return item;
        }
      });
      return targe.length > 0 ? targe[0] : {};
    },
    getParentProjectList () {
      let _list = this.parentFinttingData;
      return _list.map((item) => {
        let userTarge = this.getWorkUserList(item.pickId);
        return {
          ...item,
          carPartsId: item.carPartsId || item.id,
          id: this.fastInfo.id, //工单编辑时候的id
          pickType: userTarge.workUserType,
          pickName: userTarge.value,
          amount: Number(item.num) * Number(item.storagePrice),
        };
      });
    },
    getCarProjectLists () {
      let _list = this.parentProjectList;
      return _list.map((item) => {
        let userTarge = this.getWorkUserList(item.workUserId);
        return {
          ...item,
          carProjectId: item.carProjectId || item.id,
          id: this.fastInfo.id, //工单编辑时候的id
          projectHours: item.workHours,
          workUserType: userTarge.workUserType,
          workUserName: userTarge.value,
          amount: Number(item.workHours) * Number(item.amount), //金额
        };
      });
    },
    //开单
    async saveOrEdit () {
      const { workInfo, boutiqueList, carInfo, workInfoRemark } = this.$refs;
      let formValue = carInfo.formData;
      let formStatus = [];
      [carInfo, workInfoRemark, workInfo].map((item, index) => {
        if (item) {
          formStatus[index] = false;
          item.$refs.formData.validate((valid) => {
            if (valid) {
              formStatus[index] = true;
            }
          });
        }
      });
      if (formStatus.includes(false)) {
        return;
      }
      let { client, cars, discountInterval, member, ...data } = this.carInfo;
      let _cars = {
        ...cars,
        ...formValue.cars,
        carModelId: formValue.cars.carModels[3],
      };
      //提交对象
      let option = {
        ...formValue,
        amount: this.totalAmount, //	number总金额
        projectList: this.getCarProjectLists(), //	[...]//项目信息
        clientId: data.id,
        clientCar: _cars, //	{...}   //车辆信息
        storeId: getStoreId(), //integer($int32)门店id
        pickCarId: this.pickCarId,
      };
      if (this.fastInfo.id) {
        option.id = this.fastInfo.id;
      }
      if (this.workOrderType == 1) {
        //快速单
        option.endWash = this.endWash;
        option.couponIds = this.$refs.coupon.checkCoupon.join(","); //	string优惠券ids
        option.discountsAmount = this.couponDiscount; //	number($double)优惠金额
        option.remark = workInfoRemark.formData.remark;
      }
      if (this.workOrderType == 2) {
        //洗车单
        option.shouldAmount = this.totalAmount; //	number应收金额
        option.remark = workInfoRemark.formData.remark;
      }
      if (this.workOrderType == 3) {
        //综合单
        option.endWash = this.endWash;
        option.jpList = boutiqueList.jpList; //精品列表
        option = { ...option, ...workInfo.formData };
      }
      if (this.workOrderType == 1 || this.workOrderType == 3) {
        option.partsList = this.getParentProjectList(); //	[...] //配件列表
        option.shouldAmount = this.amountsPayable; //	number应收金额
      }
      let retMessage = {};
      let isId = !!this.fastInfo.id;
      switch (this.workOrderType) {
        case 1: //快速单
          retMessage = isId ? await editRapid(option) : await addRapid(option);
          break;
        case 2: //洗车单
          retMessage = isId ? await editWash(option) : await addWash(option);
          break; //综合单
        case 3:
          retMessage = isId ? await editSynthesize(option) : await addSynthesize(option);
          break;
      }
      if (retMessage.success) {
        this.$message.success("保存成功");
        this.closeRouter();
      }
      sessionStorage.removeItem("pendingWorkOrder");
    },
    //查询可使用优惠卷
    _couponUseCoupon () {
      this.couponDiscount = 0;
      let { id } = this.carInfo;
      if (id) {
        couponUseCoupon({
          amount: this.totalAmount,
          clientId: id,
          partsIds: this.parentFinttingData.map((i) => {
            return i.id;
          }), //配件id数组
          projectIds: this.parentProjectList.map((i) => {
            return i.id;
          }), //项目id数组
        }).then((res) => {
          let { success, data } = res;
          if (success) {
            this.couponUseCouponList = data ? data : [];
            this.couponUseCouponList.forEach((item) => (item.isActive = false));
          }
          console.log("可使用优惠", res);
        });
      }
    },
    async formatInfo () {
      let { client, clientCar, ...data } = this.fastInfo;
      console.log("详情-生成-详情信息", this.fastInfo);
      setTimeout(async () => {
        client.discountInterval = await getUserDiscount(client.id);
        this.customerInfo({
          ...client,
          cars: clientCar,
          inFactoryMileage: data.inFactoryMileage || 0,
          inFactoryOil: data.inFactoryOil || 0,
          receiveCarTime: data.receiveCarTime || "",
          receptionName: data.receptionName || "",
          workOrderCode: data.workOrderCode || "",
          sendRepairName: data.sendRepairName || "",
          sendRepairPhone: data.sendRepairPhone || "",
        });
        if (this.workOrderType == 3) {
          this.couponDiscount = data.imprest || 0;
        }
        if (this.workOrderType == 1) {
          let _couponIds = data.couponIds.split(",");
          _couponIds.forEach((item) => {
            couponDomains.forEach((item2) => {
              if (item2.id == item) {
                item2.isActive = true;
                this.couponDiscount += item2.denomination;
              }
            });
          });
          this.couponUseCouponList = couponDomains;
        }
      }, 500);
    },
  },
  async created () {
    if (this.workOrderType == 1) {
      this.debounceCoupn = debounce(this._couponUseCoupon, 1000, false); //创建查询优惠劵的啊防抖函数
    }
    let { id } = this.$route.params;
    let pickCarId = this.$route.query.pickCarId;
    if (id) {
      let option = {};
      switch (this.workOrderType) {
        case 1: //快速
          option = await rapidFindById(id);
          break;
        case 2: //洗车
          option = await editWashDetail(id);
          break;
        case 3: //综合
          option = await synthesizeFindById(id);
          break;
      }
      if (option.success) {
        this.fastInfo = option.data;
        this.formatInfo();
      }
    }
    // 接车单跳过来
    else if (pickCarId) {
      this.pickCarId = pickCarId;
      if (!id) {
        let data = this.$route.query.data;
        this.fastInfo = { ...data };
        if (data.carProjects) {
          this.fastInfo.projectList = data.carProjects;
        }
        if (data.carParts) {
          this.fastInfo.partsList = data.carParts;
        }
        this.formatInfo();
      }
    }
    //如果不是详情，则判断是否是转工单
    let obj = JSON.parse(sessionStorage.getItem("pendingWorkOrder"));
    if (obj && Object.keys(obj).length > 0) {
      let {
        type,
        carryInformation: { carProjects, carParts, car, client, ...data },
      } = obj;
      this.workOrderType = type;
      carProjects.map((item) => {
        item.discount = 10;
        item.tollType = "自费";
      });
      carParts.map((item) => {
        item.discount = 10;
        item.tollType = "自费";
      });
      this.fastInfo = {
        projectList: carProjects,
        partsList: carParts,
        clientCar: car,
        sendRepairName: client.clientName,
        sendRepairPhone: client.phone,
        client,
        id: "",
        receptionName: data.userName,
        receptionId: data.userId,
      };
      this.formatInfo();
    }
  },

  destroyed () {
    sessionStorage.removeItem("pendingWorkOrder");
  },
};
</script>
<style lang="scss" scoped>
.amount {
  font-size: 18px;
  div {
    height: 40px;
    line-height: 40px;
  }
}
.colorF40 {
  color: #f40;
}
.carList {
  cursor: pointer;
  height: 80px;
  margin-right: 20px;
  text-align: center;
  line-height: 80px;
  background-color: #ffffff;
  color: #000;
}
.activeCarList {
  cursor: pointer;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
  height: 80px;
  margin-right: 20px;
  text-align: center;
  line-height: 80px;
}
</style>
